package org.syncsoft.overalt.gui.api.window;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;

import org.syncsoft.overalt.common.api.Resource;
import org.syncsoft.overalt.gui.util.BuildFormWindow;

/**
 * 
 * @author tptfc
 *
 */
public class LoginWindow extends AbstractWindow {
	private JButton loginButton;
	
	public LoginWindow(AbstractWindowController<?> controller) {
		super(controller);
	}

	@Override
	public void setEnable(boolean enabled) {
		JTextComponent login = getTextComponent("login");
		JTextComponent password = getTextComponent("password");
		
		if (enabled) {
			login.setEditable(true);
			password.setEditable(true);
			getLoginButton().setEnabled(true);
		} else {
			login.setEditable(false);
			password.setEditable(false);
			getLoginButton().setEnabled(false);
		}
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.syncsoft.overalt.gui.swing.api.AbstractWindow#buildWindow()
	 */
	@Override
	protected void buildWindow() {
		setCreateMenu(false);
		setTitle(Resource.getProperty("overalt.label.login"));
		setSize(300, 170);
		
		
		BuildFormWindow build = new BuildFormWindow(getPanel());
		
		JLabel label;
		
		label = new JLabel(Resource.getProperty("overalt.label.login"));
		build.add(label, newTextField("login"));
		
		label = new JLabel(Resource.getProperty("overalt.label.password"));
		JTextField password = newPasswordField("password");
		password.addKeyListener(new KeyListener() {
			@Override
			public void keyTyped(KeyEvent e) {
			}
			
			@Override
			public void keyReleased(KeyEvent e) {
			}
			
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					getController().login(buildContext());
				}
			}
		});
		build.add(label, password);
		
		JButton cancelButton = new JButton(Resource.getProperty("overalt.label.cancel"));
		cancelButton.addActionListener(new QuitLoginListener());
		
		loginButton = new JButton(Resource.getProperty("overalt.label.login"));
		loginButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				getController().login(buildContext());
			}
		});
		
		setLoginButton(loginButton);
		
		build.add(cancelButton, loginButton);
	}
	
	/**
	 * 
	 * @author tptfc
	 *
	 */
	private class QuitLoginListener extends QuitListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			super.actionPerformed(e);
			getController().cancelLogin();
		}
	}

	private JButton getLoginButton() {
		return loginButton;
	}

	private void setLoginButton(JButton loginButton) {
		this.loginButton = loginButton;
	}
}
